<?php
/**
 * Theme functions file
 *
 * DO NOT MODIFY THIS FILE. Make a child theme instead: http://codex.wordpress.org/Child_Themes
 *
 * @package ClassiPress
 * @author AppThemes
 */

global $cp_options;

define(USER_SHOP, 1);
define(USER_NOMAL, 2);

// current version
$app_theme = 'ClassiPress';
$app_abbr = 'cp';
$app_version = '3.3';
$app_db_version = 1960;
$app_edition = 'Ultimate Edition';

// define rss feed urls
$app_rss_feed = 'http://feeds2.feedburner.com/appthemes';
$app_twitter_rss_feed = 'http://api.twitter.com/1/statuses/user_timeline.rss?screen_name=appthemes';
$app_forum_rss_feed = 'http://forums.appthemes.com/external.php?type=RSS2';

// define the transients we use
$app_transients = array($app_abbr.'_cat_menu');

define( 'APP_TD', 'classipress' );

// Framework
require_once( dirname( __FILE__ ) . '/framework/load.php' );

// Payments
require_once( dirname( __FILE__ ) . '/includes/payments/load.php' );

// Options
require_once( dirname( __FILE__ ) . '/includes/theme-options.php' );

scb_register_table( 'app_pop_daily', $app_abbr . '_ad_pop_daily' );
scb_register_table( 'app_pop_total', $app_abbr . '_ad_pop_total' );
APP_Mail_From::init();

require_once( dirname( __FILE__ ) . '/framework/includes/stats.php' );

if ( is_admin() )
	require_once( dirname( __FILE__ ) . '/framework/admin/importer.php' );

// Theme-specific files
require_once( dirname( __FILE__ ) . '/includes/theme-functions.php' );

//tungtt
//require_once( dirname( __FILE__ ) . '/controller/product-controller.php' );

function dump($obj){
    echo "<pre>";
    var_dump($obj);
    echo "</pre>";
}


function isAuthorOfPost($post = null){
	global $current_user;
   $isAdmin = current_user_can( 'manage_options' );
	if($post == null)
		global $post;
	if (is_user_logged_in()){
		    $authorid = $post->post_author;
    	    if($authorid == $current_user->ID ||  $isAdmin){
            	return true;
            }
         	return false;
    }
    return false;
}

//Added by Tungtt:
//Hook action này để cho user 
//không được thấy media của user khác up lên
//
add_action('pre_get_posts', 'tungtt_show_media_by_current_author_only');
function tungtt_show_media_by_current_author_only($wp_query ) {
    global $current_user;
    if( is_admin() && !current_user_can('edit_others_posts') ) {
        $wp_query->set( 'author', $current_user->ID );
    }
}

if ( current_user_can('author') && !current_user_can('upload_files') )
    add_action('admin_init', 'allow_author_uploads');

/**
 * cho phép author có thể upload hình ảnh
 */
function allow_author_uploads() {
    $author = get_role('author');
    $author->add_cap('upload_files');
}

function ys_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
     global $current_user;
     $tmpFileName = wp_unique_filename($dir, $filename, $unique_filename_callback);
     $filename = $current_user->ID."_".$tmpFileName;
     return $filename;
}
function ys_handle_upload( &$file, $overrides = false, $time = null ) {
	
        // The default error handler.
	if ( ! function_exists( 'wp_handle_upload_error' ) ) {
		function wp_handle_upload_error( &$file, $message ) {
			return array( 'error'=>$message );
		}
	}

	$file = apply_filters( 'wp_handle_upload_prefilter', $file );

	// You may define your own function and pass the name in $overrides['upload_error_handler']
	$upload_error_handler = 'wp_handle_upload_error';

	// You may have had one or more 'wp_handle_upload_prefilter' functions error out the file. Handle that gracefully.
	if ( isset( $file['error'] ) && !is_numeric( $file['error'] ) && $file['error'] )
		return $upload_error_handler( $file, $file['error'] );

	// You may define your own function and pass the name in $overrides['unique_filename_callback']
	$unique_filename_callback = null;

	// $_POST['action'] must be set and its value must equal $overrides['action'] or this:
	$action = 'wp_handle_upload';

	// Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
	$upload_error_strings = array( false,
		__( "The uploaded file exceeds the upload_max_filesize directive in php.ini." ),
		__( "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form." ),
		__( "The uploaded file was only partially uploaded." ),
		__( "No file was uploaded." ),
		'',
		__( "Missing a temporary folder." ),
		__( "Failed to write file to disk." ),
		__( "File upload stopped by extension." ));

	// All tests are on by default. Most can be turned off by $overrides[{test_name}] = false;
	$test_form = true;
	$test_size = true;
	$test_upload = true;

	// If you override this, you must provide $ext and $type!!!!
	$test_type = true;
	$mimes = false;

	// Install user overrides. Did we mention that this voids your warranty?
	if ( is_array( $overrides ) )
		extract( $overrides, EXTR_OVERWRITE );

	// A correct form post will pass this test.
	if ( $test_form && (!isset( $_POST['action'] ) || ($_POST['action'] != $action ) ) )
		return call_user_func($upload_error_handler, $file, __( 'Invalid form submission.' ));

	// A successful upload will pass this test. It makes no sense to override this one.
	if ( $file['error'] > 0 )
		return call_user_func($upload_error_handler, $file, $upload_error_strings[$file['error']] );

	// A non-empty file will pass this test.
	if ( $test_size && !($file['size'] > 0 ) ) {
		if ( is_multisite() )
			$error_msg = __( 'File is empty. Please upload something more substantial.' );
		else
			$error_msg = __( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini or by post_max_size being defined as smaller than upload_max_filesize in php.ini.' );
		return call_user_func($upload_error_handler, $file, $error_msg);
	}

	// A properly uploaded file will pass this test. There should be no reason to override this one.
	if ( $test_upload && ! @ is_uploaded_file( $file['tmp_name'] ) )
		return call_user_func($upload_error_handler, $file, __( 'Specified file failed upload test.' ));

	// A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
	if ( $test_type ) {
		$wp_filetype = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'], $mimes );

		extract( $wp_filetype );

		// Check to see if wp_check_filetype_and_ext() determined the filename was incorrect
		if ( $proper_filename )
			$file['name'] = $proper_filename;

		if ( ( !$type || !$ext ) && !current_user_can( 'unfiltered_upload' ) )
			return call_user_func($upload_error_handler, $file, __( 'Sorry, this file type is not permitted for security reasons.' ));

		if ( !$ext )
			$ext = ltrim(strrchr($file['name'], '.'), '.');

		if ( !$type )
			$type = $file['type'];
	} else {
		$type = '';
	}

	// A writable uploads dir will pass this test. Again, there's no point overriding this one.
	if ( ! ( ( $uploads = wp_upload_dir($time) ) && false === $uploads['error'] ) )
		return call_user_func($upload_error_handler, $file, $uploads['error'] );

	$filename = ys_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback );
        // Move the file to the uploads dir
	$new_file = $uploads['path'] . "/$filename";
	if ( false === @ move_uploaded_file( $file['tmp_name'], $new_file ) )
		return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) );

	// Set correct file permissions
	$stat = stat( dirname( $new_file ));
	$perms = $stat['mode'] & 0000666;
	@ chmod( $new_file, $perms );

	// Compute the URL
	$url = $uploads['url'] . "/$filename";

	if ( is_multisite() )
		delete_transient( 'dirsize_cache' );

	return apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $type ), 'upload' );
}




//include 
require_once( dirname( __FILE__ ) . '/model/product-model.php' );



/**
 * Addeb by TungTT
 * Action này dùng trong trường hợp:
 * -Request 1 url không tồn tại
 * -Request 1 url không có quyền truy cập
 * -Request 1 url phải yêu cầu login 
 */
function my_page_template_redirect()
{
    $template_link = get_page_template();
    //add new product 
    if(strpos($template_link, "tpl-add-product.php")!=FALSE){
        # Ê, login chưa mà đòi vô hả mày.
        if (!is_user_logged_in()) {
            #Chưa login, éo cho vào, vô login nha con.
            $currentUrl =  urlencode (get_permalink()); 
            $loginUrl = get_permalink( get_page_by_path( 'Login' ) ) ;
            
            
            $loginUrl =$loginUrl."&redirect_url=".$currentUrl;
            wp_redirect($loginUrl);
            exit;
        }
       
    }
    $isRedirect = FALSE;
    if(strpos($template_link, "tpl-product-single.php")!=FALSE){
        if (!isset($_GET["pid"]) || empty($_GET["pid"])) {
            $isRedirect = TRUE;
        } 
    }
    if($isRedirect == TRUE){
//        echo "redirect đi đó nha";
        //wp_redirect(home_url('/404/'));
//        exit();
    }
}
add_action( 'template_redirect', 'my_page_template_redirect' );


/*
 * Added by Tung
 * Thay đổi configure mặc định trong Editor của wp
 * Ngắn gọn đơn giản hơn.
 */
add_filter( 'tiny_mce_before_init', 'tungtt_advmceconf_config_mce', 1111 );
function tungtt_advmceconf_config_mce( $config ) {
	global $plugin_page;
        if ( ! empty( $plugin_page ) && $plugin_page == 'advanced-tinymce-configuration/adv-mce-config.php' ) {
		global $advmceconf_show_defaults;
                $advmceconf_show_defaults = $config;
		return $config;
	}
        $options = array(
                "theme_advanced_buttons1" => "bold,italic,underline,bullist,numlist,justifyleft,justifycenter,justifyright,link,unlink,formatselect,forecolor",
                "theme_advanced_buttons2" => ""
            );
//        update_option('advmceconf_options', $options);
//        $options = get_option('advmceconf_options');

	if ( empty( $options ) || !is_array( $options ) )
		return $config;

	return array_merge( $config, $options );
}

/**
 * Added by TungTT
 * Cái này để thay đổi teamplate header
 * Trường hợp chúng ta muốn dùng một header riêng
 */
function tungtt_header_hook() {
    $template_link = get_page_template();//Lấy template link hiện tại
    $isRedirect = FALSE;
    //Nếu nó là trang hiện thị chi tiết sản phẩm
    if(strpos($template_link, "tpl-product-single.php")!=FALSE){
//        echo "Header riêng cho chi tiết sản phẩm";
    }
}
add_action( 'get_header', 'tungtt_header_hook' );


/**
 * Added by Tung
 * Get last time activity
 * ví dụ: 5 giây trước, 1 tháng trước, 1 năm trước,...
 */
function ys_humanTiming ($time)
{
    $deltatime = time() - $time; // to get the time since that moment
    $tokens = array (
        31536000 => 'năm',
        2592000 => 'tháng',
        604800 => 'tuần',
        86400 => 'ngày',
        3600 => 'giờ',
        60 => 'phút',
        1 => 'giây'
    );

    foreach ($tokens as $unit => $text) {
        if ($deltatime < $unit) continue;
        $numberOfUnits = floor($deltatime / $unit);
        return $numberOfUnits.' '.$text." trước";
    }

}

/**
 * Added by Tung
 * get id of a page by filename
 * query from database
 * @param :$filename
 * @return id of filename
 */

function get_id_by_filename($filename) {
    $page_q = new WP_Query(array(
                'post_type' => 'page',
                'meta_key' => '_wp_page_template',
                'meta_value' => $filename
                    ));
    if (empty($page_q->posts))
        $page_id = 0;
    else
        $page_id = $page_q->posts[0]->ID;
    return $page_id;
}

/**
 * Hook template
 * Dùng trong trường hợp chúng ta muốn có một trang nào đó
 * có một dạng template riêng biệt và không liên quan gì đến cái đang dùng
 * 
 * @param $template : template mặc định đang dùng, nếu trường hợp
 * chúng ta tìm không ra template của mình thì nó sẽ dùng cái template
 * mặc định này
 */
//function tungtt_template_hook( $template ) {
//        $new_template = locate_template( array( 'tpl-ct-test.php' ) );
//        var_dump($new_template);
//        echo $template;
//        if ( '' != $new_template ) {
//                return $new_template ;
//        }
//        return $template;
//}
//add_filter( 'single_template',tungtt_template_hook , 99 );
#change default WP Editor


/**
 * Lấy các file image default
 * 
 */
function getDefaultImage($ImageFor){
    $templateUri = get_template_directory_uri()."/images/";
    switch($ImageFor){
        case "single_product_default":
            return $templateUri."/default_product_image.jpg";
            break;
            
        default:
            return $templateUri."/default_product_image.jpg";
            break;
    }
}

require_once( dirname( __FILE__ ) . '/controller/test.php' );
//require_once( dirname( __FILE__ ) . '/controller/category-controller.php' );
//require_once( dirname( __FILE__ ) . '/controller/product-controller.php' );
require_once( dirname( __FILE__ ) . '/controller/follow-controller.php' );
require_once( dirname( __FILE__ ) . '/controller/user-controller.php' );
require_once( dirname( __FILE__ ) . '/controller/common-controller.php' );
require_once( dirname( __FILE__ ) . '/controller/product.php' );

